let chatUser = sessionStorage.getItem('chatUser')
if (!chatUser) {
    window.location.href = './login.html'
}
let user = { user: chatUser }
let sendBtn = document.querySelector('.send-btn')
let textarea = document.querySelector('textarea')
let records = document.querySelector('.records')
const socket = io.connect('http://47.106.159.148:3000')
socket.emit('login',user)
socket.on('login', obj => {
    user = obj
})
socket.on('refreshUserList',arr=>{
})
socket.on('newUser', obj => {
    let div = document.createElement('div')
    div.classList.add('new-user')
    div.innerText = `"${obj.user}"加入了摸鱼事务所`
    records.appendChild(div)
})
socket.on('leaveUser', obj => {
    let div = document.createElement('div')
    div.classList.add('leave-user')
    div.innerText = `"${obj.user}"离开了摸鱼事务所`
    records.appendChild(div)
})
socket.on('message', obj => {
    let wrapDiv = document.createElement('div')
    let contentDiv = document.createElement('div')
    let nameDiv = document.createElement('div')
    if (obj.sid === user.sid) {
        wrapDiv.classList.add('self-wrap')
        contentDiv.classList.add('self-content')
        contentDiv.innerText = obj.message
        wrapDiv.appendChild(contentDiv)
        textarea.value = ''
    } else {
        wrapDiv.classList.add('others-wrap')
        contentDiv.classList.add('others-content')
        nameDiv.classList.add('others-name')
        nameDiv.innerText = obj.user
        contentDiv.innerText = obj.message
        wrapDiv.appendChild(nameDiv)
        wrapDiv.appendChild(contentDiv)
    }
    records.appendChild(wrapDiv)
    records.scrollTop = records.scrollHeight
})
sendBtn.onclick = function () {
    socket.emit('message',{user:chatUser,message:textarea.value})
}

document.onkeydown = function (event) {
    if (event.code === 'Enter') {
        socket.emit('message',{user:chatUser,message:textarea.value})
    }
}
document.onmousedown = function (event) {
    if (event.target.id === 'send-btn') {
        event.preventDefault()
    }
}